home *** CD-ROM | disk | FTP | other *** search
- Path: colossus.holonet.net!russell
- From: russell@news.mdli.com (Russell Blackadar)
- Newsgroups: comp.lang.c++
- Subject: Re: Proper use of friend keyword
- Date: 1 Apr 1996 20:17:04 GMT
- Organization: HoloNet National Internet Access System: 510-704-1058/modem
- Message-ID: <4jpdk0$sds@colossus.holonet.net>
- References: <4jn3qk$3tl6@holly.ACNS.ColoState.EDU>
- NNTP-Posting-Host: jubal.mdli.com
- X-Newsreader: TIN [version 1.2 PL2]
-
- Corby S. Hudnall (corbyh@holly.ACNS.ColoState.EDU) wrote:
- > Hey all, I have a question about how to use the friend keyword. Consider
- > the following example:
- ...
- > class ABC
- > {
- > int AValue;
- > int GetAValue() { return (AValue); }
- ...
- > };
- > class XYZ
- ...
- > friend int ABC::GetAValue();
- > };
-
- > void main()
- ^^^^ NO, should be int main() !!
-
- > {
- > ABC abc;
- > XYZ xyz;
- > cout << xyz.GetAValue() << endl
- ^^^ NO, see below
- ...
-
- Friendship does not change a member's ownership -- so no matter
- what you do, you can't call GetAValue for an XYZ object. Moreover,
- you can't just grab a class's private members (ABC::GetAValue) by
- declaring friendship -- ABC has to *grant* friendship. In other
- words, if you want ABC::GetAValue to be callable from outside ABC,
- the friend declaration must be *inside* ABC. The friend declaration
- names the function which is allowed to *call* GetAValue (as well as
- call other private members of ABC).
-
- In the above, the function calling ABC::GetAValue is main, so to
- "make this work" you would need
- friend int main();
- inside your ABC definition; and then you'd write
- cout << abc.GetAValue() << endl;
- in main. Of course, it would be frivolous and inadvisable to grant
- friendship to main; much more useful examples abound in C++ textbooks
- and I recommend you do some reading.
-
- Good luck!
- --
- Russell Blackadar, russell@mdli.com
-